package com.woniuxy.system.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.woniuxy.system.entity.RoleUrlPermission;
import com.woniuxy.system.mapper.RoleUrlPermissionMapper;
import com.woniuxy.system.model.dto.RolePermissionDto;
import com.woniuxy.system.service.IRoleUrlPermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 角色与菜单、接口权限的对应关系 服务实现类
 * </p>
 *
 * @author 作者
 * @since 2023-10-13
 */
@Service
public class RoleUrlPermissionServiceImpl extends ServiceImpl<RoleUrlPermissionMapper, RoleUrlPermission> implements IRoleUrlPermissionService {

    @Transactional
    @Override
    public void roleAuthorization(RolePermissionDto rolePermissionDto) {
        // 先删除原有的角色对应的权限： delete from role_user_permission where role_id=1
        baseMapper.delete(Wrappers.lambdaQuery(RoleUrlPermission.class)
                .eq(RoleUrlPermission::getRoleId,rolePermissionDto.getRoleId()));

        // 遍历所有的权限，添加角色权限关系： insert into role_user_permission(url_permission_id,role_id)..
        Long[] permissionIds = rolePermissionDto.getPermissionIds();
        if (permissionIds != null && permissionIds.length > 0) {
            for (Long permissionId : permissionIds) {
                RoleUrlPermission roleUrlPermission = new RoleUrlPermission();
                roleUrlPermission.setRoleId(rolePermissionDto.getRoleId());
                roleUrlPermission.setUrlPermissionId(permissionId);
                baseMapper.insert(roleUrlPermission);
            }
        }
    }
}
